﻿using C1.WPF;
using C1.WPF.Chart.Annotation;
using C1.WPF.Extended;
using C1.WPF.FlexGrid;
using Model.Modules;
using Proxy;
using SteelDetection.UIControl;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using Utility;
using ViewModel;

namespace SteelDetection
{
    /// <summary>
    /// PageHistory.xaml 的交互逻辑
    /// </summary>
    public partial class PageHistory : Page
    {
        List<UCRulerchart> charts;
        public PageHistory()
        {
            InitializeComponent();
            Loaded += PageHistory_Loaded;

            var binding = new Binding();
            binding.Mode = BindingMode.OneWayToSource;
            binding.Path = new PropertyPath("CurrentImg");
            this.SetBinding(CurrentImgProperty, binding);
            this.SetBinding(CurrentBatchProperty, "CurrentBatch");
            this.SetBinding(SteelDefectlistProperty, "ShownSteelDefects");
            this.SetBinding(CurrentSteelDefectProperty, new Binding("CurrentSteelDefect") { Mode = BindingMode.TwoWay });
            this.SetBinding(SteelSourceLoadingProperty, new Binding("SteelSourceLoading") { Mode = BindingMode.TwoWay });
            radochart.AllChartLoaded += (charts) =>
            {
                this.charts = charts;
            };

            radochart.CurrentSteelDefectChanged += (steel_defect) =>
            {
                if (steel_defect == null)
                {
                    floatviewer.Visibility = Visibility.Collapsed;
                }
                else
                {
                    this.SetValue(CurrentSteelDefectProperty, steel_defect);
                    floatviewer.Visibility = Visibility.Visible;
                }
            };
            batchgrid.ColumnHeaders.Rows[0].Height = 50;
            imagedefectgrid.ColumnHeaders.Rows[0].Height = 50;
            //radochart.SelectedSteelDefectsChanged += (steel_defects) =>
            //{
            //    if (steel_defects.Any())
            //    {
            //        floatviewer.Visibility = Visibility.Visible;
            //        this.SetValue(CurrentSteelDefectProperty, steel_defects.First());
            //    }
            //};
            

        }

        private void PageHistory_Loaded(object sender, RoutedEventArgs e)
        {
            SteelDefectlist.CollectionChanged += SteelDefectlist_CollectionChanged;
            steeldefectgrid.ColumnHeaders.Rows[0].Height = 40;
            imagedefectgrid.ColumnHeaders.Rows[0].Height = 40;
            //steeldefectgrid.Columns[4].ValueConverter = new ColumnValueConverter(new Dictionary<bool, string>() { { false, "否" }, { true, "是" } });
            steeldefectgrid.Columns[2].ValueConverter= new ColumnValueConverter(Defectypes.GetInstance(),"id","name");
            (this.DataContext as VM_PageHistory).RequestShowDialog += (s, ee) =>
            {
                DefectTypeDlg dlg = new DefectTypeDlg();
                var dlgresult = dlg.ShowDialog();
                if ((bool)dlgresult == true)
                {
                    
                    ee.Callback(dlg.Dtype);
                }
            };

            Loaded -= PageHistory_Loaded;
        }

        #region DependencyProperty依赖属性

        private void SteelDefectlist_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                UpdateRectAnnos(e.NewItems as ObservableCollection<steel_defect>);
            }
            else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset)
            {
                ClearAnnos();
            }
        }

        public ObservableCollection<steel_defect> SteelDefectlist
        {
            get { return (ObservableCollection<steel_defect>)GetValue(SteelDefectlistProperty); }
            set { SetValue(SteelDefectlistProperty, value); }
        }
        public static readonly DependencyProperty SteelDefectlistProperty = DependencyProperty.RegisterAttached("SteelDefectlist", typeof(ObservableCollection<steel_defect>), typeof(PageHistory), new FrameworkPropertyMetadata(null, new PropertyChangedCallback((d, e) =>
        {
            (d as PageHistory).ClearAnnos();
            if (e.NewValue != null)
            {
                Logger.Info("客户端缺陷数量：" + (e.NewValue as ObservableCollection<steel_defect>).Count().ToString());
                var defects = e.NewValue as ObservableCollection<steel_defect>;
                if (defects.Any())
                {
                    (d as PageHistory).UpdateRectAnnos(e.NewValue as ObservableCollection<steel_defect>);
                }

            }
        })));

        public steel_defect CurrentSteelDefect
        {
            get { return (steel_defect)GetValue(CurrentSteelDefectProperty); }
            set { SetValue(CurrentSteelDefectProperty, value); }
        }
        public static readonly DependencyProperty CurrentSteelDefectProperty = DependencyProperty.RegisterAttached("CurrentSteelDefect", typeof(steel_defect), typeof(PageHistory), new FrameworkPropertyMetadata(null, new PropertyChangedCallback((d, e) =>
        {
            if (e.NewValue != null)
            {
                if ((d as PageHistory).SteelSourceLoading)
                {
                    //(d as PageHistory).steeldefectgrid.Select(-1, -1);
                    //(d as PageHistory).floatviewer.Visibility = Visibility.Collapsed;
                    return;
                }
                (d as PageHistory).radochart.ChangeCurrentSteelDefectAnno(e.NewValue as steel_defect);
                (d as PageHistory).floatviewer.Visibility = Visibility.Visible;
            }
        })));

        public batch CurrentBatch
        {
            get { return (batch)GetValue(CurrentBatchProperty); }
            set { SetValue(CurrentBatchProperty, value); }
        }
        public static readonly DependencyProperty CurrentBatchProperty = DependencyProperty.RegisterAttached("Curren", typeof(batch), typeof(PageHistory), new FrameworkPropertyMetadata(null, new PropertyChangedCallback((d, e) =>
        {
            if (e.NewValue != null && e.OldValue != null)
            {
                (d as PageHistory).floatviewer.Visibility = Visibility.Collapsed;
                //(d as PageHistory).ClearAnnos();
            }
        })));

        public Imagedefectinfo CurrentImg
        {
            get
            {
                return (Imagedefectinfo)GetValue(CurrentImgProperty);
            }
            set
            {
                SetValue(CurrentImgProperty, value);
            }
        }
        public static readonly DependencyProperty CurrentImgProperty = DependencyProperty.RegisterAttached("CurrentImg", typeof(Imagedefectinfo), typeof(PageHistory), new FrameworkPropertyMetadata(null, new PropertyChangedCallback((s, e) =>
        {
            if (e.NewValue != null)
            {
                //ObservableCollection<Imagedefectinfo> imagedefectinfos = e.NewValue as ObservableCollection<Imagedefectinfo>;
                //foreach (var info in imagedefectinfos)
                //{
                //    (s as PageHistory).radochart.AddIconFont(new Point((double)info.Image.left_edge, (double)info.Image.camera_id), (double)info.Image_DefectList[0].type);
                //}
            }
        })));

        public bool SteelSourceLoading
        {
            get { return (bool)GetValue(SteelSourceLoadingProperty); }
            set { SetValue(SteelSourceLoadingProperty, value); }
        }
        public static readonly DependencyProperty SteelSourceLoadingProperty = DependencyProperty.RegisterAttached("SteelSourceLoading", typeof(bool), typeof(PageHistory), new FrameworkPropertyMetadata(false, new PropertyChangedCallback((d, e) =>
        {
            if (e.NewValue != null && e.NewValue != e.OldValue)
            {

            }
        })));

        #endregion

        public async void UpdateRectAnnos(ObservableCollection<steel_defect> defectinfos)
        {
            _ = radochart.Dispatcher.BeginInvoke(new Action(() => { radochart.UpdateRectAnnos(defectinfos); }));
        }
        public void ClearAnnos()
        {
            radochart.ClearAnnos();
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            floatviewer.Visibility = Visibility.Collapsed;
        }

        private void Detail_SelectedItemChanged(object sender, EventArgs e)
        {
            var item = (sender as C1.WPF.FlexGrid.C1FlexGrid).SelectedItem;
            CurrentImg = (Imagedefectinfo)item;
            //用于更新单选选中的图像缺陷
            if (this.DataContext != null)
                (this.DataContext as VM_PageHistory).SelectedImageDefects = new ObservableCollection<Imagedefectinfo>(imagedefectgrid.SelectedItems.Cast<Imagedefectinfo>());
        }
        private void MasterGrid_SelectedItemChanged(object sender, EventArgs e)
        {
            var grid = sender as C1FlexGrid;
            var item = (sender as C1FlexGrid).SelectedItem;
            grid.ScrollIntoView(grid.Selection.Row, 0);
        }
        private void steeldefectgrid_SelectionChanged(object sender, CellRangeEventArgs e)
        {
            //用于更新多选选中的钢材缺陷
            if (this.DataContext != null)
                (this.DataContext as VM_PageHistory).SelectedSteelDefects = new ObservableCollection<steel_defect>(steeldefectgrid.SelectedItems.Cast<steel_defect>());
        }

        private void imagedefectgrid_SelectionChanged(object sender, CellRangeEventArgs e)
        {
            //用于更新多选选中的图像缺陷
            if (this.DataContext != null)
                (this.DataContext as VM_PageHistory).SelectedImageDefects = new ObservableCollection<Imagedefectinfo>(imagedefectgrid.SelectedItems.Cast<Imagedefectinfo>());
        }


        private void C1ComboBox_SelectedIndexChanged(object sender, PropertyChangedEventArgs<int> e)
        {
            return;
            var selectitem = (sender as C1ComboBox).SelectedItem;
            if (selectitem == null) return;
            string filter = (selectitem as C1ComboBoxItem).Content.ToString();
            switch (filter)
            {
                case "全部":
                    batchgrid.CollectionView.Filter = null;
                    break;
                case "优秀":
                    batchgrid.CollectionView.Filter = IsExcellent;
                    break;
                case "良好":
                    batchgrid.CollectionView.Filter = IsGood;
                    break;
                case "较差":
                    batchgrid.CollectionView.Filter = IsPoor;
                    break;
            }
        }

        private bool IsExcellent(object obj)
        {
            if (obj as batch != null
               && (obj as batch).grade == "优秀")
            {
                return true;
            }
            return false;
        }
        private bool IsGood(object obj)
        {
            if (obj as batch != null
               && (obj as batch).grade == "良好")
            {
                return true;
            }
            return false;
        }
        private bool IsPoor(object obj)
        {
            if (obj as batch != null
               && (obj as batch).grade == "较差")
            {
                return true;
            }
            return false;
        }

        bool steelSourceLoading = false;
        private void steeldefectgrid_ItemsSourceChanging(object sender, EventArgs e)
        {
            steeldefectgrid.SelectedIndex = -1;
            SteelSourceLoading = true;

        }

        private void steeldefectgrid_ItemsSourceChanged(object sender, EventArgs e)
        {
            SteelSourceLoading = false;
        }


        private void AddCusotmIdCommand(object sender, RoutedEventArgs e)
        {
            
        }


        private void C1Expander_IsMouseOverChanged(object sender, PropertyChangedEventArgs<bool> e)
        {
            //(sender as C1Expander).IsExpanded = e.NewValue;
        }

        private void C1Expander_IsExpandedChanged(object sender, PropertyChangedEventArgs<bool> e)
        {
            
        }

        private void batchgrid_SelectedItemChanged(object sender, EventArgs e)
        {
            batchexpander.IsExpanded = false;
        }

        private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            var hitinfo = batchgrid.HitTest(e.GetPosition(batchgrid));
            var batch = batchgrid.Rows[hitinfo.Row].DataItem;
            (this.DataContext as VM_PageHistory).AddCusotmIdCommand_Executed(batch);
        }

        private async void steeldefectgrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var hitinfo = steeldefectgrid.HitTest(e);
            if (hitinfo.Column != 0)
            {
                floatviewer.Visibility = Visibility.Visible;
            }
            else
            {
                var repeatDefect=await new ESDataHelper().GetRepeatDefectByID((steeldefectgrid.SelectedItem as steel_defect).repeat_id);
                MessageBox.Show($"缺陷类型：{repeatDefect.defect_type}\r周期数：{repeatDefect.repeat_num}\r周期长度：{repeatDefect.repeat_len}", "周期性缺陷");
            }

        }

        private void imagedefectgrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            floatviewer.Visibility = Visibility.Visible;
        }

        private void HandleReviewDefect(object sender, RoutedEventArgs e)
        {
            if(!string.IsNullOrEmpty(hittestMain_id))
                VM_WindowMain.GetInstance().GotoReviewDefect(hittestMain_id);
        }

        string hittestMain_id="";
        private void batchgrid_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            hittestMain_id = "";
            var hitinfo = batchgrid.HitTest(e);
            if(hitinfo.CellType== CellType.Cell)
                hittestMain_id = (batchgrid.Rows[hitinfo.Row].DataItem as batch).main_id;
            
        }

        private void GoToNextDetect(object sender, RoutedEventArgs e)
        {
            steeldefectgrid.SelectedIndex = Math.Min(steeldefectgrid.Rows.Count - 1, steeldefectgrid.SelectedIndex + 1);
            steeldefectgrid.ScrollIntoView(steeldefectgrid.SelectedIndex, 0);

        }

        private void GoToPreviousDetect(object sender, RoutedEventArgs e)
        {
            steeldefectgrid.SelectedIndex = Math.Max(0, steeldefectgrid.SelectedIndex - 1);
            steeldefectgrid.ScrollIntoView(steeldefectgrid.SelectedIndex, 0);
        }
    }




}
